package com.xiaozhen.coap.server;

import com.xiaozhen.coap.resource.TestResource;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.network.config.NetworkConfig;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/10/13 16:11
 * @description:
 */
@Component
public class TestServer extends CoapServer {

    @Override
    public synchronized void start() {
        // add the resource to the server, the resource name here is ‘test’ which is corresponding
        // to the uri in the client
        super.add(new TestResource("test"));
        try {
            this.myAddEndPoint();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        System.out.println("sever start");
        super.start();
    }

    public void myAddEndPoint() throws UnknownHostException {
        // get the NetworkConfig object of californium
        NetworkConfig config = NetworkConfig.getStandard();
        String ip = "0.0.0.0";
        InetAddress addr = InetAddress.getByName(ip);
        //5683 is the default port
        InetSocketAddress bindToAddress = new InetSocketAddress(addr, 5683);
        // create a new endpoint
        CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
        builder.setInetSocketAddress(bindToAddress);
        builder.setNetworkConfig(config);
        // add the endpoint to the server
        super.addEndpoint(builder.build());
    }
}
